package com.vcaresolution.logistic.util;

import java.beans.PropertyEditorSupport;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;

import org.springframework.util.StringUtils;

import com.vcaresolution.util.Utils;

public class CustomDateEditor extends PropertyEditorSupport {

	private final boolean allowEmpty;

	/**
	 * Create a new CustomDateEditor instance, using the given DateFormat for
	 * parsing and rendering.
	 * <p>
	 * The "allowEmpty" parameter states if an empty String should be allowed
	 * for parsing, i.e. get interpreted as null value. Otherwise, an
	 * IllegalArgumentException gets thrown in that case.
	 *
	 * @param dateFormat DateFormat to use for parsing and rendering
	 * @param allowEmpty if empty strings should be allowed
	 */
	public CustomDateEditor(final DateFormat dateFormat, final boolean allowEmpty) {
		this.allowEmpty = allowEmpty;
	}

	/**
	 * Parse the Date from the given text, using the specified DateFormat.
	 */
	@Override
	public void setAsText(final String text) throws IllegalArgumentException {
		if (allowEmpty && !StringUtils.hasText(text)) {
			// Treat empty String as null value.
			setValue(null);
		} else {
			try {
				final boolean isValidDate = Utils.isValidDate(text);

				if(!isValidDate) {
					throw new IllegalArgumentException("Could not parse date: ");
				}
				setValue(ApplicationConstants.DEFAULT_DDMMYYYY_DATE_FORMAT.parse(text));
			} catch (final ParseException ex) {
				throw new IllegalArgumentException("Could not parse time: " + ex.getMessage(), ex);
			}
		}
	}

	/**
	 * Format the Date as String, using the specified DateFormat.
	 */
	@Override
	public String getAsText() {
		final Date value = (Date) getValue();
		return (value != null ? ApplicationConstants.DEFAULT_DDMMYYYY_DATE_FORMAT.format(value) : "");
	}

}
